from PyQt5.QtWidgets import QDialog
from PyQt5.QtGui import QColor
from Processor.contrast.contrast_design import Ui_ContrastDialog

import time
import cv2
import numpy as np
import Processor.Converter as Converter


class ContrastDialog(QDialog, Ui_ContrastDialog):
    layer = None    # 图层
    mat = None  # 原始Mat 数据

    def __init__(self, parent, mat=None):
        super().__init__(parent)
        self.setupUi(self)
        self.initUI(parent)
        self.mat = mat

    def initUI(self, parent):
        self.setWindowTitle('对比度')
        # 定位
        self.resize(320, 52)
        pos = parent.geometry()
        self.move((pos.width() - self.width())/2, (pos.height() - self.height())/2)
        #       信号
        self.horizontalSlider_contrast.valueChanged.connect(self.updateSlot)
        self.horizontalSlider_brightness.valueChanged.connect(self.updateSlot)
        # 数据
        contrast = self.horizontalSlider_contrast.value() / 100
        brightness = self.horizontalSlider_brightness.value()
        self.label_contrast.setText('{:.2f}'.format(contrast))
        self.label_brightness.setText('{:d}'.format(brightness))

    def updateSlot(self):
        contrast = self.horizontalSlider_contrast.value() / 100
        brightness = self.horizontalSlider_brightness.value()
        self.label_contrast.setText('{:.2f}'.format(contrast))
        self.label_brightness.setText('{:d}'.format(brightness))
        self.__contrast(contrast, brightness)

    def __contrast(self, contrast=1, brightness=0):
        start = time.clock()
        mat = self.mat.copy()
        print('c',contrast)
        print('b',brightness)
        mat = np.uint8(np.clip(contrast * mat + brightness, 0, 255))
        image = Converter.Numpy2QImage(mat)
        end = time.clock()
        print('contrast', '耗时：', end - start)
        self.layer.updatePixmap(image)


def newContrast(window):
    """
    :param window: 主窗体
    :return:
    """
    layer = window.currentLayer
    if layer:
        image = layer.image  # 当前图层QImage句柄
        mat = Converter.QImage2Numpy(image)
        controller = ContrastDialog(window, mat)
        controller.layer = layer
        if controller.exec_():
            pass
